package com.smartthinking.dive;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Dictionary;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class UpdateDB extends Activity{

//	public static ArrayList<Dictionary> TraeDatos = null;
	public String dbversion = null;
	public int flag = 0;
	public int error = 0;

	@Override
	public void onBackPressed() {
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ui_update_db);

		Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

		if(isSDPresent)
		{
			// yes SD-card is present
			StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
			double sdAvailSize = (double)stat.getAvailableBlocks()
					* (double)stat.getBlockSize();
			//One binary gigabyte equals 1,073,741,824 bytes.
			int megaAvailable = (int)(sdAvailSize / 1073741.824);
			if(megaAvailable > 15){
				Toast.makeText(getApplicationContext(), R.string.st_iniciando_descarga_, Toast.LENGTH_LONG).show();
				Bundle extras = getIntent().getExtras();
				if(extras != null){
					dbversion = extras.getString("dbversion");
				}

				final ProgressBar progress = (ProgressBar)findViewById(R.id.progress_update);
				final TextView    textview = (TextView)findViewById(R.id.text_update);
				new MyWorker(UpdateDB.this, progress, textview).execute();
			}else{
				Toast.makeText(getApplicationContext(), R.string.st_no_hay_espacio_suficiente_en_la_sdcard, Toast.LENGTH_LONG).show();
			}
		}
		else
		{
			Toast.makeText(getApplicationContext(), R.string.st_se_requiere_de_una_sdcard_para_realizar_la_descarga, Toast.LENGTH_LONG).show();
		}
	}


	final class MyWorker extends AsyncTask<Void, Integer, Void> {

		ArrayList<Dictionary<String, String> > TraeDatos = null;
		
		private final String titles[] = {"5%",
//				"10%",
//				"11%",
//				"12%",
//				"17%", 
//				"22%", 
//				"23%",
//				"34%",
//				"37%",
//				"43%",
//				"48%",
//				"53%",
//				"63%",
//				"73%",
//				"74%",
//				"79%",
//				"80%",
//				"81%",
//				"83%",
//				"84%",
//				"85%",
//				"87%",
//				"93%",
//				"94%",
				"10%",
				"15%",
				"20%",
				"25%",
				"35%",
				"45%", 
				"55%", 
				"65%",
				"75%",
				"85%",
				"95%",
		"100%"};


//		private final int progr[]  = {5, 5, 1, 1,5, 5, 1, 11,3, 6, 5, 5, 10, 10, 1, 5, 1, 1, 2, 1, 1, 2, 6, 1, 6};
		private final int progr[]  = {5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 10, 10, 5};

		private int index;

//		private final Activity parent;
		private ProgressBar progress;
		private TextView textview;

		public MyWorker(final Activity parent, final ProgressBar progress, final TextView textview) {
			
//			this.parent = parent;
			this.progress = progress;
			this.textview = textview;
		}

		@Override
		protected void onPreExecute() {

			int max = 0;
			for (final int p : progr) {
				max += p;
			}
			progress.setMax(max);
			index = 0;
		}

//		@SuppressWarnings("unchecked")
		@Override
		protected Void doInBackground(final Void... params) {
			try{
				if(Utilities.isNetwork()){
					//					new MyWorker(getApplicationContext(), UpdateDB.this.progress, textview).execute();
					DatabaseHelper usdbh = new DatabaseHelper(getApplicationContext());
					SQLiteDatabase db = usdbh.getWritableDatabase();
					String qry_web = null, qry_local = null;
//					Utilities util = new Utilities();
					//Create Folder
//					File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Squenda");
//					if(!folder.exists()){
//						folder.mkdirs();
//						Log.i("FOLDER CREATED", "Squenda");
//					}else{
//						Log.i("FOLDER ALREADY CREATED", "Squenda");
//					}
					
					File path=new File(getApplicationContext().getFilesDir(),"localdata");
			        if(path.mkdirs()){
			        	Log.i("mkdirs","mkdirs");
			        }else{
			        	Log.i("else","else");
			        }

					//Si hemos abierto correctamente la base de datos
					if(db != null)
					{
						try{
							db.execSQL("DELETE FROM pois");
							db.execSQL("DELETE FROM estado");
							db.execSQL("DELETE FROM categorias");
							db.execSQL("DELETE FROM subcategorias");
							db.execSQL("DELETE FROM pois_subcategorias");
							db.execSQL("DELETE FROM eventos");
							db.execSQL("DELETE FROM banners");
							db.execSQL("DELETE FROM perfiles");
							db.execSQL("DELETE FROM modulos");
							db.execSQL("DELETE FROM permisos_modulos");
							db.execSQL("DELETE FROM pois_estados");
							db.execSQL("DELETE FROM telefono");
							

						}catch (Exception e) {
							e.printStackTrace();
						}

						
						/*********POIS**********/

						qry_web  = "select * from pois";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS POIS", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String poi_idr = dic.get("poi_idr").toString();
							String poi_nombre = dic.get("poi_nombre").toString();
							String poi_lat = dic.get("poi_lat").toString();
							String poi_lng = dic.get("poi_lng").toString();
							String poi_direccion = dic.get("poi_direccion").toString();
							String poi_colonia = dic.get("poi_colonia").toString();
							String poi_municipio = dic.get("poi_municipio").toString();
							String poi_cp = dic.get("poi_cp").toString();
							String poi_telefono1 = dic.get("poi_telefono1").toString();
							String poi_telefono2 = dic.get("poi_telefono2").toString();
							String poi_telefono3 = dic.get("poi_telefono3").toString();
							String poi_telefono4 = dic.get("poi_telefono4").toString();
							String poi_mail = dic.get("poi_mail").toString();
							String poi_www = dic.get("poi_www").toString();
							String poi_thumb = dic.get("poi_thumb").toString();
							String poi_horarios = dic.get("poi_horarios").toString();
							String poi_facebook = dic.get("poi_facebook").toString();
							String poi_twitter = dic.get("poi_twitter").toString();
							String poi_youtube = dic.get("poi_youtube").toString();
							String poi_mail2 = dic.get("poi_mail2").toString();
							String poi_skype = dic.get("poi_skype").toString();
							String poi_pdf = dic.get("poi_pdf").toString();
							String poi_desc = dic.get("poi_desc").toString();
//							String cat_cve = dic.get("cat_cve").toString();
							String edo_cve = dic.get("edo_cve").toString();
							String poi_destacado = dic.get("poi_destacado").toString();
							String poi_activo = dic.get("poi_activo").toString();
							poi_thumb = poi_thumb.trim().replace(" ", "%20");
							poi_pdf = poi_pdf.trim().replace(" ", "%20");

							if(poi_thumb.equals("null"))
								poi_thumb = "";
							if( poi_thumb.length() > 0 ){
								poi_thumb = verifyFile(""+poi_thumb);
							}
							if(poi_pdf.equals("null"))
								poi_pdf = "";
							if( poi_pdf.length() > 0 ){
								poi_pdf = verifyFile(""+poi_pdf);
							}
							qry_local = "insert into pois(poi_idr, poi_nombre, poi_lat, poi_lng, poi_direccion, poi_colonia, poi_municipio, " +
									"poi_cp, poi_telefono1, poi_telefono2, poi_telefono3, poi_telefono4, poi_mail, poi_www, poi_thumb, " +
									"poi_horarios, poi_facebook, poi_twitter, poi_youtube, poi_skype, poi_mail2, poi_pdf, poi_desc, edo_cve, poi_destacado, poi_activo)"+
									"values ('"+poi_idr+"', '"+poi_nombre+"', '"+poi_lat+"', '"+poi_lng+"', '"+poi_direccion+"', '"+poi_colonia+"', " +
											"'"+poi_municipio+"', '"+poi_cp+"', '"+poi_telefono1+"', '"+poi_telefono2+"', '"+poi_telefono3+"', " +
											"'"+poi_telefono4+"', '"+poi_mail+"', '"+poi_www+"', '"+poi_thumb+"', '"+poi_horarios+"', " +
											"'"+poi_facebook+"', '"+poi_twitter+"', '"+poi_youtube+"', '"+poi_mail2+"', '"+poi_skype+"', '"+poi_pdf+"', '"+poi_desc+"', '"+edo_cve+"', '"+poi_destacado+"', '"+poi_activo+"')";
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						
						
						
						
						
						
						/*********ESTADOS**********/

						qry_web  = "select * from estado";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS ESTADOS", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String edo_cve = dic.get("edo_cve").toString();
							String edo_des = dic.get("edo_des").toString();
							
							qry_local = "insert into estado(edo_cve, edo_des)"+
									"values ('"+edo_cve+"', '"+edo_des+"')";
							
							db.execSQL(qry_local);
						}
						publishProgress();
						
						/*********CATEGORIAS**********/

						qry_web  = "select * from categorias";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS CATEGORIAS", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String cat_cve = dic.get("cat_cve").toString();
							String cat_des = dic.get("cat_des").toString();
							
							qry_local = "insert into categorias(cat_cve, cat_des)"+
									"values ('"+cat_cve+"', '"+cat_des+"')";
							
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						
						
						
						
						
						
						
						/*********SUBCATEGORIAS**********/

						qry_web  = "select * from subcategorias";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS SUBCATEGORIAS", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String sub_cve = dic.get("sub_cve").toString();
							String cat_cve = dic.get("cat_cve").toString();
							String sub_des = dic.get("sub_des").toString();
							
							qry_local = "insert into subcategorias(sub_cve, cat_cve, sub_des)"+
									"values ('"+sub_cve+"', '"+cat_cve+"', '"+sub_des+"')";
							Log.i("QRY LOCAL",""+qry_local);
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						
						
						
						/*********POIS_SUBCATEGORIAS**********/

						qry_web  = "select * from pois_subcategorias";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS POIS_SUBCATEGORIAS", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String poi_idr = dic.get("poi_idr").toString();
							String sub_cve = dic.get("sub_cve").toString();
							String cat_cve = dic.get("cat_cve").toString();
							
							
							qry_local = "insert into pois_subcategorias(poi_idr,sub_cve, cat_cve)"+
									"values ( "+poi_idr+","+sub_cve+","+cat_cve+")";
							Log.i("QRY LOCAL",""+qry_local);
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						
						
						
						
						/*********EVENTOS**********/

						qry_web  = "select * from eventos";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS EVENTOS", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String eve_idr = dic.get("eve_idr").toString();
							String eve_nombre = dic.get("eve_nombre").toString();
							String eve_descripcion = dic.get("eve_descripcion").toString();
							String eve_poster = dic.get("eve_poster").toString();
							String eve_fec_ini = dic.get("eve_fec_ini").toString();
							String eve_fec_fin = dic.get("eve_fec_fin").toString();
//							String eve_plano = dic.get("eve_plano").toString();
							String eve_lugar = dic.get("eve_lugar").toString();
							String eve_contacto = dic.get("eve_contacto").toString();
							String eve_contacto2 = dic.get("eve_contacto2").toString();
							String eve_mail = dic.get("eve_mail").toString();
							String eve_tel = dic.get("eve_tel").toString();
							String eve_tel2 = dic.get("eve_tel2").toString();
							String eve_tel3 = dic.get("eve_tel3").toString();
							String eve_tel4 = dic.get("eve_tel4").toString();
							String eve_facebook = dic.get("eve_facebook").toString();
							String eve_twitter = dic.get("eve_twitter").toString();
//							String eve_youtube = dic.get("eve_youtube").toString();
//							String eve_linkedin = dic.get("eve_linkedin").toString();
//							String eve_mail_preregistro = dic.get("eve_mail_preregistro").toString();
							String eve_www = dic.get("eve_www").toString();
//							String eve_orden = dic.get("eve_orden").toString();
//							String eve_publicado = dic.get("eve_publicado").toString();
//							String eve_lugar_en = dic.get("eve_lugar_en").toString();
							String eve_proveedores = dic.get("eve_proveedores").toString();
							String eve_hora_ini = dic.get("eve_hora_ini").toString();
							String eve_hora_fin = dic.get("eve_hora_fin").toString();
							String eve_lat = dic.get("eve_lat").toString();
							String eve_lng = dic.get("eve_lng").toString();
							String eve_pdf = dic.get("eve_pdf").toString();
							String eve_destacado = dic.get("eve_destacado").toString();
							String eve_activo = dic.get("eve_activo").toString();
							String eve_direccion = dic.get("eve_direccion").toString();
							String eve_colonia = dic.get("eve_colonia").toString();
							String eve_municipio = dic.get("eve_municipio").toString();
							String eve_cp = dic.get("eve_cp").toString();
							String edo_cve = dic.get("edo_cve").toString();
							
							eve_poster = eve_poster.trim().replace(" ", "%20");
							eve_pdf = eve_pdf.trim().replace(" ", "%20");
							
							if(eve_poster.equals("null"))
								eve_poster = "";
							if( eve_poster.length() > 0 ){
								eve_poster = verifyFile(""+eve_poster);
							}
							
							if(eve_pdf.equals("null"))
								eve_pdf = "";
							if( eve_pdf.length() > 0 ){
								eve_pdf = verifyFile(""+eve_pdf);
							}
							qry_local = "insert into eventos(eve_idr, eve_nombre, eve_descripcion, eve_poster, eve_fec_ini, eve_fec_fin,"+
									"eve_lugar, eve_contacto,eve_contacto2, eve_mail, eve_tel, eve_tel2, eve_tel3, eve_tel4, eve_facebook, eve_twitter, eve_proveedores, eve_www, eve_hora_ini, " +
									"eve_hora_fin, eve_lat, eve_lng, eve_pdf, eve_destacado, eve_activo, eve_direccion, eve_colonia, eve_municipio, eve_cp, edo_cve) "+
									"values ('"+eve_idr+"', '"+eve_nombre+"', '"+eve_descripcion+"', '"+eve_poster+"', '"+eve_fec_ini+"', '"+eve_fec_fin+"', " +
									" ' "+eve_lugar+"', '"+eve_contacto+"','"+eve_contacto2+"', '"+eve_mail+"', '"+eve_tel+"', '"+eve_tel2+"', '"+eve_tel3+"', '"+eve_tel4+"', ' "+eve_facebook+"', '"+eve_twitter+"', " +
									" ' "+eve_proveedores+"', '"+eve_www+"', '"+eve_hora_ini+"', '"+eve_hora_fin+"', '"+eve_lat+"', '"+eve_lng+"', '"+eve_pdf+"', '"+eve_destacado+"','"+eve_activo+"', " +
									" '"+eve_direccion+"', '"+eve_colonia+"', '"+eve_municipio+"', '"+eve_cp+"', '"+edo_cve+"')";
							
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						
						
						
						
						
						
						
						/*********BANNERS**********/

						qry_web  = "select * from banners";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS BANNERS", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String ban_idr = dic.get("ban_idr").toString();
							String ban_tipo = dic.get("ban_tipo").toString();
							String ban_url = dic.get("ban_url").toString();
							String ban_timer = dic.get("ban_timer").toString();
							String ban_tamano = dic.get("ban_tamano").toString();
							String ban_destino_url = dic.get("ban_destino_url").toString();
							String ban_activo = dic.get("ban_activo").toString();

							ban_url = ban_url.trim().replace(" ", "%20");
							ban_destino_url = ban_destino_url.trim().replace(" ", "%20");

							if(ban_url.equals("null"))
								ban_url = "";
							if( ban_url.length() > 0 ){
								ban_url = verifyFile(""+ban_url);
							}
							
//							if(ban_destino_url.equals("null"))
//								ban_destino_url = "";
//							if( ban_destino_url.length() > 0 ){
//								ban_destino_url = verifyFile(""+ban_destino_url);
//							}
							
							qry_local = "insert into banners(ban_idr, ban_tipo, ban_url, ban_timer, ban_tamano, ban_destino_url, ban_activo) " +
									"values ('"+ban_idr+"', '"+ban_tipo+"', '"+ban_url+"', '"+ban_timer+"', '"+ban_tamano+"', '"+ban_destino_url+"', "+ban_activo+")";
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						
						
						
						
						
						
						
						
						
						
						/*********PERFILES**********/

						qry_web  = "select * from perfiles";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS PERFILES", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String per_idr = dic.get("per_idr").toString();
							String per_nombre = dic.get("per_nombre").toString();
							
							qry_local = "insert into perfiles(per_idr, per_nombre)"+
									"values ('"+per_idr+"', '"+per_nombre+"')";
							
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						
						
						
						
						

						
						
						
						
						/*********MODULOS**********/

						qry_web  = "select * from modulos";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS MODULOS", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String mod_idr = dic.get("mod_idr").toString();
							String mod_des = dic.get("mod_des").toString();
							
							qry_local = "insert into modulos(mod_idr, mod_des)"+
									"values ('"+mod_idr+"', '"+mod_des+"')";
							
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						
						
						
						
						
						
						
						
						/*********PERMISOS_MODULOS**********/

						qry_web  = "select * from permisos_modulos";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS PERMISOS_MODULOS", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String per_idr = dic.get("per_idr").toString();
							String mod_idr = dic.get("mod_idr").toString();
							
							qry_local = "insert into permisos_modulos(per_idr, mod_idr)"+
									"values ('"+per_idr+"', '"+mod_idr+"')";
							
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						/*********POIS_ESTADOS**********/

						qry_web  = "select * from pois_estados";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS POIS_ESTADOS", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String poi_idr = dic.get("poi_idr").toString();
							String edo_cve = dic.get("edo_cve").toString();
							
							qry_local = "insert into pois_estados(poi_idr, edo_cve)"+
									"values ('"+poi_idr+"', '"+edo_cve+"')";
							
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						/*********TELEFONO**********/

						qry_web  = "select * from telefono";
						TraeDatos = Utilities.qry(UpdateDB.this,qry_web.replace(" ", "%20"));
						Log.i("REGISTROS TELEFONO", ""+TraeDatos.size());
						for(int i = 0; i < TraeDatos.size(); i++){
							Dictionary dic = TraeDatos.get(i);
							String tel_num = dic.get("tel_num").toString();
							
							qry_local = "insert into telefono(tel_num)"+
									"values ('"+tel_num+"')";
							
							db.execSQL(qry_local);
						}
						publishProgress();
						
						
						
						SharedPreferences preferences = UpdateDB.this.getSharedPreferences("prefs", MODE_PRIVATE);
						SharedPreferences.Editor editor = preferences.edit();
						editor.putString("dbversion", dbversion).commit();

						publishProgress();

						db.close();
					}
				}else{
					flag  = 1;
				}



			}catch (Exception e) {
				e.printStackTrace();
				error = 1;
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(final Integer... values) {
			textview.setText(""+titles[index]);
			progress.incrementProgressBy(progr[index]);
			++index;
		}

		@Override
		protected void onPostExecute(final Void result) {
			if(error == 0){
				if(flag == 0){
					AlertDialog.Builder ad = new AlertDialog.Builder(UpdateDB.this);  
					ad.setTitle(R.string.st_evento_descargado_exitosamente);  
					ad.setMessage(R.string.st_ahora_puede_);   
					ad.setPositiveButton(R.string.st_aceptar, new DialogInterface.OnClickListener() {  
						public void onClick(DialogInterface dialog, int id) {  
							dialog.dismiss();
							finish();

						}  
					});  
					ad.show();
				}else{
					AlertDialog.Builder ad = new AlertDialog.Builder(UpdateDB.this);  
					ad.setTitle(R.string.st_no_hay_conexi_n_a_internet);  
					ad.setMessage(R.string.st__reintentar_);   
					ad.setPositiveButton("Sí", new DialogInterface.OnClickListener() {  
						public void onClick(DialogInterface dialog, int id) {  
							new MyWorker(UpdateDB.this, progress, textview);
						}  
					}).setNegativeButton("No", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});  
					ad.show();
				}
			}else{
				AlertDialog.Builder ad = new AlertDialog.Builder(UpdateDB.this);  
				ad.setTitle(R.string.st_error);  
				ad.setMessage(R.string.st_se_perdi_la_conexi_n_a_internet);   
				ad.setPositiveButton(R.string.st_aceptar, new DialogInterface.OnClickListener() {  
					public void onClick(DialogInterface dialog, int id) {  
						finish();
					}  
				});  
				ad.show();
			}
		}


		public String verifyFile(String ban_url) {
			String ban_url_ruta = "";
			String nombre = "";
			if (ban_url.length()==0) {
				return ban_url_ruta;
			}
			if (ban_url.equals("null")) {
				return ban_url_ruta;
			}
			if (ban_url.equals("http://squenda.smartthinking.com.mx/")) {
				return ban_url_ruta;
			}
			if (ban_url.equals("http://squenda.smartthinking.com.mx/null")) {
				return ban_url_ruta;
			}
			nombre = ban_url.substring(11,ban_url.length());
			Log.i("ban_nombre", ""+nombre);

			//		    File file = getFileStreamPath(Environment.getExternalStorageDirectory()+"Pediatria/"+nombre);
			if(fileExistsInSD(nombre)){
				Log.i("FILE EXISTS", "FILE EXISTS");
			}else{
				try {     

					Log.i("FILE DOESNT EXIST", "FILE DOESNT EXIST");
					URL url = new URL ("http://squenda.smartthinking.com.mx/contenidos/"+nombre);
					URLConnection connection = url.openConnection();
					connection.setConnectTimeout(10000);
					//					connection.getInputStream();
					//					InputStream input = url.openStream(); 
					InputStream input = connection.getInputStream(); 

//					File storagePath = Environment.getExternalStorageDirectory();
//					OutputStream output = new FileOutputStream (storagePath+ "/Squenda/"+nombre);  
					OutputStream output = new FileOutputStream (getApplicationContext().getFilesDir()+"/localdata/"+nombre);  

					
					Log.i("location", output.toString());
					try {         
						byte[] buffer = new byte[1024];         
						int bytesRead = 0;         
						while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
							output.write(buffer, 0, bytesRead);         
						}     
					}catch (Exception e) {
						e.printStackTrace();
					}   
					finally {         
						output.close();  
						input.close(); 

					} 
				}catch (Exception e) {
					e.printStackTrace();
				} 
				Log.i("file storage", "file storage");

			}


			return nombre;
		}


		public boolean fileExistsInSD(String sFileName){
			String sFolder = getApplicationContext().getFilesDir()+"/localdata";

//			String sFolder = Environment.getExternalStorageDirectory().toString() +  "/Squenda";
			String sFile=sFolder+"/"+sFileName;
			java.io.File file = new java.io.File(sFile);
			return file.exists();
		}
	}





}

